<template>
  <section>
    <!--工具条 高级查询 新增和修改-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>


    <!--
      :data="pets" - 绑定数据
      highlight-current-row - 当前行高亮
      v-loading="listLoading" - 加载框 = 盲等框
      @selection-change="selsChange" - 选中事件
    -->
    <!--列表 删除-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称" width="100">
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="100">
      </el-table-column>
      <el-table-column prop="saleprice" label="销售价" width="100">
      </el-table-column>
      <el-table-column prop="type.name" label="宠物类型" width="100">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80">
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state==1">上架</span>
          <span style="color: red" v-else-if="scope.row.state==0">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="100">
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="100">
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="100">
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" width="100">
      </el-table-column>
      <el-table-column prop="user.username" label="领养人" width="100">
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" width="100">
        <template scope="scope">
          <span style="color: green" v-if="scope.row.searchMasterMsgId">寻主消息</span>
          <span style="color: red" v-else>店铺饲养</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条：批量删除和分页栏-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--
      :title="title"  - 标题
      :visible.sync="saveFormVisible" - 是否显示对画框 - 默认不显示
      :close-on-click-modal="false" - 在对话框外面点击不关闭

      :model="saveForm"  -  绑定表单
      label-width="80px" -
      :rules="saveFormRules" - 表单的验证规则
      ref="saveForm" - 为当前对话框取名 - 方便验证表单
    -->
    <!--新增或修改界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false" width="80%">
      <el-form :model="saveForm" label-width="100px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型" prop="type">
          <el-cascader v-model="saveForm.type"
                       :options="typeTree"
                       :props="{ checkStrictly: true, label:'name',value:'id' }" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="宠物图片" prop="resources">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="宠物状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属店铺" prop="shopId">
          <!--<el-input v-model="saveForm.shopId" auto-complete="off"></el-input>-->
          <el-select v-model="saveForm.shopId" clearable placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice">
          <quill-editor v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {getPetListPage, removePet, batchRemovePet, editPet, addPet} from '../../api/api';

//引入Vue的ueditor的资源
import {quillEditor} from "vue-quill-editor"; //调用编辑器
import quillConfig from '../../common/js/quill-config';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

export default {
  components: {
    quillEditor
  },
  //定义模型数据
  data() {
    return {
      quillOption: quillConfig,

      //1.数据列表相关模型数据
      pets: [], //列表数据
      listLoading: false, //加载框 - 默认不显示

      //2.分页查询数据
      totals: 0,
      currentPage: 1,
      pageSize: 5,

      //3.高级查询数据
      keyword: '',

      //4.批量删除
      sels: [],//列表选中列

      //5.添加或修改
      title: '', //标题
      saveFormVisible: false,//添加和修改对话框是否显示
      saveLoading: false,  //保存的忙等框 - 在提交按钮上
      saveFormRules: {     //表单项验证规则
        name: [
          {required: true, message: '请输入宠物名称', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入成本价', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入销售价', trigger: 'blur'}
        ],
      },

      //编辑界面数据 ：建议字符串用''，id用null
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        type: null,
        resources: '',
        state: 0,
        shopId: null,
        petDetail: {  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      },

      //所属店铺
      shops: [],

      //宠物类型树
      typeTree: [],

      //显示图片的集合
      fileList: []
    }

  },

  //定义方法
  methods: {
    //1.获取用户列表
    getPets() {
      let para = {
        "currentPage": this.currentPage,
        "pageSize": this.pageSize,
        //高级查询 -- 关键字查询
        "keyword": this.keyword
      };
      //显示加载框
      this.listLoading = true;
      this.$http.post("/pet", para).then(res => {
        //关闭加载框
        this.listLoading = false;
        //显示分页数据
        this.pets = res.data.data;
        //计算分页栏
        this.totals = res.data.totals;
      }).catch(res => {
        this.$message.error('网络繁忙,请稍后重试');
      })
    },

    //2.点击当前页的逻辑
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },

    //3.关键字查询
    keywordQuery() {
      this.currentPage = 1;
      this.getPets();
    },


    //4.删除功能
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {//确认框
        type: 'warning'
      }).then(() => { //点击确认的时候
        this.listLoading = true;//开启加载框
        this.$http.delete("/pet/" + row.id).then(res => {
          this.listLoading = false; //关闭加载框
          if (res.data.success) { //成功
            this.$message.success("删除成功");
            //对当前页的处理
            let totalPage = Math.ceil(this.totals / this.pageSize); //算出总页数
            //如果当前页是最后一页         并且  并且是最后一条数据              并且  不是第一页
            if (this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
              //当前页 = 当前页-1(上一页)
              this.currentPage = this.currentPage - 1;
            }
            //再次调用
            this.getPets();
          } else {
            this.$message.error("网络繁忙,请稍后重试【500】");
          }
        }).catch(res => {
          this.$message.error("网络繁忙,请稍后重试【400,404】");
        })
      }).catch(() => { //点击取消的时候
      });
    },

    //5.选项改变时触发
    selsChange: function (sels) {
      this.sels = sels;
    },

    //6.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {//点击确认时
        //开启加载框
        this.listLoading = true;
        this.$http.patch("/pet", ids).then(res => {
          //关闭加载框
          this.listLoading = false;
          if (res.data.success) {//删除成功
            //弹出成功信息
            this.$message.success("删除成功");
            //重置到第一页
            this.currentPage = 1;
            //重新获取新数据
            this.getPets();
          } else {
            this.$message.error("网络繁忙,请稍后重试【500】");
          }
        }).catch(res => {
          this.$message.error("网络繁忙,请稍后重试【400,404】");
        })
      }).catch(() => { //点击取消时
      });
    },


    //7.显示编辑界面
    handleEdit: function (index, row) {
      //回显数据：避免以前的数据发生改变
      this.saveForm = Object.assign({}, row);
      this.title = "修改";

      if (this.saveForm.type) {
        //对宠物类型回显的处理 {} -- []
        var dirPath = this.saveForm.type.dirPath; // 2/3/7 - [2,3,7]
        var arr = dirPath.split("/")
        var arr1 = [];
        for (var i = 1; i < arr.length; i++) {
          arr1[i - 1] = parseInt(arr[i]); //将字符串转成整数
          //第一次 arr1[0] = arr[1] = 2
          //第二次 arr1[1] = arr[2] = 3
          //第三次 arr1[2] = arr[3] = 7
        }
        this.saveForm.type = arr1;
      }


      this.getPets();
      this.getShops();
      this.getTypeTree();

      //处理fileList - 点击修改能够回显图片
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if (this.saveForm.resources) {
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url": "http://123.207.27.208" + item});
        }
      }

      //显示对话框
      this.saveFormVisible = true;
    },


    //8.显示新增界面
    handleAdd: function () {
      this.title = "新增";
      this.saveForm = {
        id: null,
        name: '',
        costprice: null,
        saleprice: null,
        typeId: null,
        type: null,
        resources: '',
        state: 0,
        shopId: null,
        petDetail: {  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      };
      this.getPets();
      this.getShops();
      this.getTypeTree();

      //清空fileList的数据
      this.fileList = [];

      //显示对话框
      this.saveFormVisible = true;
    },

    //9.新增或修改
    saveSubmit: function () {
      //所有的对话框中 的 名称为saveForm的对话框  验证上面的表单项验证通过就返回true
      this.$refs.saveForm.validate((valid) => { //表单验证
        if (valid) {//表单验证通过
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //开启加载框
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);

            //点击提交对类型的处理
            let typeArr = this.saveForm.type; //[2,3,7]
            if (typeArr) {
              //前端传递type为数组，后端type接收的是PetType类型，如果不处理就会报400错误
              para.type = null;
              //将修改之后的宠物类型id赋值给typeId
              para.typeId = typeArr[typeArr.length - 1]
            }


            this.$http.put("/pet", para).then(res => {
              //关闭忙等框
              this.saveLoading = false;
              //关闭对话框
              this.saveFormVisible = false;
              if (res.data.success) {
                //弹出成功信息
                this.$message.success("操作成功");
                //重新获取新的数据
                this.getPets();
              } else {
                this.$message.error("网络繁忙，请稍后重试!!!【500】");
              }
            }).catch(res => {
              this.$message.error("网络繁忙，请稍后重试!!!【400,404】")
            })
          });
        }
      });
    },

    //10.查询所有店铺
    getShops() {
      this.$http.get("/shop").then(res => {
        this.shops = res.data;
      })
    },

    //11.宠物部门树
    getTypeTree() {
      this.$http.get("/petType/typeTree").then(res => {
        this.typeTree = res.data;
      })
    },

    //12.文件上传的业务逻辑
    handleSuccess(response, file, fileList) {
      //Object { success: true, msg: "操作成功", resultObj: "/group1/M00/00/E4/CgAIC2Lc91yAK-XNAAVL-CQTDAM697.jpg" }
      //1.对resources的处理 - 添加到数据库
      if (this.saveForm.resources) { //有值返回true
        this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
      } else {
        this.saveForm.resources = response.resultObj;
      }

      //2.对list的处理 - 前端显示图片
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新难过的数据】
      if (this.saveForm.resources) {
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i];  // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url": "http://123.207.27.208" + item});
        }
      }
    },

    //13.点击删除图片之后对resources【操作数据库】和fileList【前台显示】做处理，并且调用删除接口删除图片
    handleRemove(file, fileList) {
      //1.调用删除接口删除图片
      //Object { url:"http://123.207.27.208/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg"}
      var path = file.url.substring(file.url.indexOf("/group1")); //  /group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg
      this.$http.delete("/fastDfs?path=" + path).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
        } else {
          this.$message.error("删除失败");
        }
      })

      //2.对resource做处理
      // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg,/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      if (this.saveForm.resources) {
        var arr = this.saveForm.resources.split(",");
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i];
          if (path == item) { //找到了删除的图片
            arr.splice(i, 1);//删除指定的图片
          }
        }
        this.saveForm.resources = arr.join(",");
      }

      //3.对list的处理 - 前端显示图片
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新难过的数据】
      if (this.saveForm.resources) {
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i];  // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url": "http://123.207.27.208" + item});
        }
      }
    },

    //上架
    onsale(){
      if(this.sels.length==0){//没有选
        this.$message.warning("没有选中上架的宠物!!!");
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => { //点击确定
        var ids = this.sels.map(item => item.id);//[1,2,3]
        this.$http.post("/pet/onsale",ids).then(res=>{
          if(res.data.success){
            this.$message.success("上架成功");
            this.getPets();
          }else{
            this.$message.warning(res.data.msg);
          }
        }).catch(res=>{
          this.$message.warning("系统繁忙【400,404】");
        })
      }).catch(() => {
      });
    },

    //下架
    offsale(){
      if(this.sels.length==0){//没有选
        this.$message.warning("没有选中下架的宠物!!!");
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => { //点击确定
        var ids = this.sels.map(item => item.id);//[1,2,3]
        this.$http.post("/pet/offsale",ids).then(res=>{
          if(res.data.success){
            this.$message.success("下架成功");
            this.getPets();
          }else{
            this.$message.warning("系统繁忙【500】");
          }
        }).catch(res=>{
          this.$message.warning("系统繁忙【400,404】");
        })
      }).catch(() => {
      });
    }
  },

  //页面加载完成就执行
  mounted() {
    this.getPets();
  }
}

</script>

<style scoped>

</style>